package com.hnl.action.talent;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.HNLPageDispatch;
import com.hnl.core.aware.HNLAuthAware;
import com.hnl.core.aware.HNLTalentAware;
import com.hnl.core.aware.MiscTypeAware;
import com.hnl.dao.DAOException;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.dao.ReferralDAO;
import com.hnl.to.Referral;
import com.hnl.to.wrapper.ReferralWrapper;
import com.hnl.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class DeleteReferral extends HttpServlet implements HNLAuthAware,
		HNLTalentAware, MiscTypeAware, HNLPageDispatch {
	public static final Logger LOG = LoggerFactory
			.getLogger(DeleteReferral.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		try {
			// delete
			Integer talentID = Integer.parseInt(req
					.getParameter(ATTRIBUTE_TALENT_ID));
			String delString = req.getParameter(ATTRIBUTE_DELETE_LIST);
			ReferralDAO referralDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getReferralDAO();
			String[] delLists = delString.split(",");
			for (String list : delLists) {
				String[] ids = list.split("_");
				Integer rID = Integer.parseInt(ids[0]);
				Integer tID = Integer.parseInt(ids[1]);
				referralDAO.deleteReferral(rID, tID);
			}

			Collection<ReferralWrapper> Referrals = new Vector<ReferralWrapper>();
			Collection<Referral> referralCollection = referralDAO
					.loadReferral(talentID);
			for (Referral referral : referralCollection) {
				ReferralWrapper aReferral = new ReferralWrapper(referral);
				aReferral.getReferralName();
				Referrals.add(aReferral);
			}

			writer.println(JSONResponseUtil.getJSONObjectString(Referrals));

		} catch (DAOException e) {
			LOG.error("Error to delete Talent", e);
		} finally {
			writer.close();
		}
	}

}
